package com.ssrs.framework.web.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ssrs.framework.util.SpringUtil;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @author ssrs
 */
public class AsyncManager {
    private static final Log log = LogFactory.get(AsyncManager.class);
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;
    private final long TIMEOUT = 120L;

    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = (ScheduledExecutorService) SpringUtil.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();

            try {
                if (!executor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                    if (!executor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
                        log.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException var2) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
